//前端技术(五)—— 使用Node.js编写简单的项目
//https://blog.csdn.net/m0_74825502/article/details/144201796
const express = require('express');
const path = require("node:path");
const cors = require("cors");
const config = require("./config.js");
const { expressjwt } = require("express-jwt");

const app = express();

const joi=require("joi");

app.use(function(err, req, res, next) {
    if(err instanceof joi.ValidationError) {
        return res.cc(err)
    }
    res.cc(err)
})

app.use(expressjwt({secret:config.jwtSecretKey,algorithms: ["HS256"]}).unless({path:[/^\/api\//]}));

app.use(cors());

app.use(express.urlencoded({ extended: false}));

app.use((req, res, next) => {
    res.cc=(err,status=1)=>{
        res.send({
            status,
            message:err instanceof Error ? err.message:err
        })
    }
    next()
})

const userRouter = require("./router/user");
//const res = require("express/lib/response");
app.use('/api',userRouter);

app.use((err,req,res,next)=>{
    if(err instanceof joi.ValidationError) { return res.cc(err)}
    if(err.name === 'UnauthorizedError') {return res.cc('UnauthorizedError',1)}
    res.cc(err);
});

app.listen(8080,()=>{
    // console.log(app);
    // console.log(path.join(__dirname, '..'));
    console.log('api server listening on port 8080');
});